package com.niiuzu.client.screen.feed.viewer;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.niiuzu.client.i18n.FeedMessages;

/**
 * Implémentation de la vue pour la consultation des données provenant des flux
 * RSS.
 */
public class FeedViewerViewImpl extends Composite implements FeedViewerView {

	private static final String CSS_FEDD_SUMMARY = "feedEntrySummary";

	/**
	 * Interface {@link UiBinder} adaptée à la vue {@link FeedViewerViewImpl}.
	 */
	interface SuitedUiBinder extends UiBinder<Widget, FeedViewerViewImpl> {

	}

	@UiField
	FlexTable feedTable;

	private FeedMessages feedMessages;

	private DateTimeFormat dateTimeFormat;

	@Override
	public void createView() {
		SuitedUiBinder uiBinder = GWT.create(SuitedUiBinder.class);
		initWidget(uiBinder.createAndBindUi(this));

		feedMessages = GWT.create(FeedMessages.class);

		String dateFormat = feedMessages.entryDateFormat();
		dateTimeFormat = DateTimeFormat.getFormat(dateFormat);
	}

	@Override
	public String toString() {
		return this.getClass().toString();
	}

	@Override
	public void addFeedEntry(String link, ImageResource icon,
			String channelGroupName, Date date, String summary) {

		CellFormatter cellFormatter = feedTable.getCellFormatter();

		int row = feedTable.getRowCount();
		int col = 0;

		String strDate = "-";
		if (date != null) {
			strDate = dateTimeFormat.format(date);
		}

		feedTable.setWidget(row, col++, new Image(icon));
		feedTable.setHTML(row, col++, channelGroupName);
		feedTable.setHTML(row, col++, strDate);

		feedTable.setHTML(row, col, summary);
		cellFormatter.addStyleName(row, col++, CSS_FEDD_SUMMARY);

		Anchor anchor = new Anchor(feedMessages.entryGoTo(), link, "_blank");
		feedTable.setWidget(row, col++, anchor);
	}

	@Override
	public void clearAllFeedData() {
		feedTable.removeAllRows();
	}
}
